/**
 * Copyright (c) 2019-2029, wwww.kiwipeach.cn (liuburu@qq.com).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * <p>
 * https://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package cn.kiwipeach.blog.utils;

import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Method;

/**
 * 描述：操作系统行为工具类
 *
 * @author kiwipeach
 * @since 2.0
 */
@Slf4j
public class SystemRuntimeUtil {

    /**
     * 不同操作系统使用默认浏览器打开链接
     *
     * @param url 地址
     */
    public static void browerOpen(String url) {
        // 获取操作系统的名字
        String osName = System.getProperty("os.name", "");
        // windows
        try {
            if (osName.startsWith("Windows")) {
                //Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + url);
                Runtime.getRuntime().exec("cmd /c start " + url);
                // Mac
            } else if (osName.startsWith("Mac OS")) {
                Class fileMgr = Class.forName("com.apple.eio.FileManager");
                Method openURL = fileMgr.getDeclaredMethod("openURL", String.class);
                openURL.invoke(null, url);
            } else {
                // Unix or Linux
                String[] browsers = {"firefox", "opera", "konqueror", "epiphany", "mozilla", "netscape"};
                String browser = null;
                // 执行代码，在brower有值后跳出，
                for (int count = 0; count < browsers.length && browser == null; count++) {
                    // 这里是如果进程创建成功了，==0是表示正常结束。
                    if (Runtime.getRuntime().exec(new String[]{"which", browsers[count]}).waitFor() == 0) {
                        browser = browsers[count];
                    }
                }
                if (browser == null) {
                    throw new RuntimeException("未找到任何可用的浏览器");
                } else {// 这个值在上面已经成功的得到了一个进程。
                    Runtime.getRuntime().exec(new String[]{browser, url});
                }
            }
        } catch (Exception e) {
            log.error("打开应用错误:{}", e.getMessage());
        }
    }

}
